<template>
  <a-modal v-model='showModal' @ok='confirmOk' @cancel='cancel' :title='titles' width='70%'>
    <a-spin :spinning='loading'>
      <a-form :form='form'>
        <a-row :gutter='[24, 0]'>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='服务名称' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <a-input
                placeholder='请输入'
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }]
                  }
                ]"
                maxLength='30'
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='是否支持上门' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <a-select
                class='flex-1'
                @change='onChange2'
                placeholder='请选择'
                v-decorator="['onsit', { rules: [{ required: true, message: '请选择' }] }]"
              >
                <a-select-option :value='1'>是</a-select-option>
                <a-select-option :value='0'>否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='[24, 0]'>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='服务图片' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <PreviewImage
                :showUpload='isShow'
                class='mt-12'
                :is-preview='false'
                :scene='8'
                :show-upload='formgetFileLength(`picUrls`) < 1'
                @uploadSuccess='formuploadSuccess($event, `picUrls`)'
                accept=".png,.jpg"
                v-decorator="[
                  `picUrls`,
                  {
                    rules: [{ required: true, message: '请上传图片', type: 'array' }],
                    initialValue: []
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='服务宣传视频' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <a-upload @change='handleChange'
                        accept='.mp4'
                        action='http://cwqd.ricecs.cn/admin-api/system/file/upload'
                        :file-list='fileList'
                        :headers="{'Authorization':token}"

              >
                <a-button>
                  <a-icon type='upload' />
                  上传
                </a-button>
              </a-upload>
              <video :src='videoUrl' style='width: 100%;height: 120px' controls></video>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='[24, 0]'>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='服务分类' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <div style='display: flex;'>
                <a-select
                  class='flex-1'
                  @change='changeSelectCate'
                  placeholder='请选择'
                  v-decorator="['firstCategoryId', { rules: [{ required: true, message: '请选择' }] }]"
                >
                  <a-select-option :value='item.id' v-for='item in cateList'>{{ item.name }}</a-select-option>
                </a-select>
                <a-select
                  class='flex-1'
                  @change='changeSelectCate2'
                  placeholder='请选择'
                  v-decorator="['secondCategoryId']"
                >
                  <a-select-option :value='item.id' v-for='item in cateList2'>{{ item.name }}</a-select-option>
                </a-select>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='[24, 0]'>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='服务价格' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <div style='display:flex'>
                <a-input
                  placeholder='请输入'
                  v-decorator="[
                    'price',
                    {
                      rules: [{ required: true, message: '请输入' }]
                    }
                  ]"
                  maxLength='30'
                ></a-input
                >
                元
              </div>
            </a-form-item>
          </a-col>

        </a-row>

        <a-row :gutter='[24, 0]'>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='所属店铺' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <a-select
                class='flex-1'
                placeholder='请选择'
                @change='onChange'
                v-decorator="['storeId', { rules: [{ required: true, message: '请选择' }] }]"
              >
                <a-select-option :value='item.id' v-for='item in storeList'>{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item class='mb-15' label='状态' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <a-switch
                checked-children='已上架'
                un-checked-children='未上架'
                v-decorator="['status', { valuePropName: 'checked' }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='[24, 0]'>
          <a-col :span='24'>
            <a-form-item class='mb-15' label='商品简介' :label-col='{ span: 4 }' :wrapper-col='{ span: 20 }'>
              <a-textarea
                placeholder='请输入'
                v-decorator="[
                  'introduction',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }]
                  }
                ]"
                maxLength='300'
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      <!--  <div>服务档期设置：</div>
        <a-row :gutter='24'>
          <a-col :span='24'>
            <a-tabs :default-active-key='activeKey'>
              <a-tab-pane :key='index' v-for='(item, index) in dateList'>
                <span slot='tab'>
                  <div>{{ item.week }}</div>
                  <div>{{ item.date }}</div>
                </span>
                <div class='time'>
                  <div
                    v-for='(items, indexs) in item.times'
                    :key='indexs'
                    :class="indexs == timeCurt ? 'active' : ''"
                    @click='changeTime(indexs)'
                  >
                    {{ items }}
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-col>
        </a-row> -->
        <div class='mt-20 mb-20'>产品详情：</div>
        <a-row :gutter='24'>
          <a-col :span='24'>
            <quill-editor
              class='editor'
              v-model='content'
              ref='myQuillEditor'
              :options='editorOption'
              @blur='onEditorBlur($event)'
              @focus='onEditorFocus($event)'
              @change='onEditorChange($event)'
              @ready='onEditorReady($event)'
            >
            </quill-editor>
          </a-col>
        </a-row>
        <div class='mt-20 mb-20'>购买须知：</div>
        <a-row :gutter='24'>
          <a-col :span='24'>
            <quill-editor
              class='editor'
              v-model='content2'
              ref='myQuillEditor'
              :options='editorOption'
              @blur='onEditorBlur2($event)'
              @focus='onEditorFocus2($event)'
              @change='onEditorChange2($event)'
              @ready='onEditorReady2($event)'
            >
            </quill-editor>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import storage from '@/utils/storage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { get } from 'lodash'
import { productList, storelist, serviceupdate, servicecreate, serviceget } from '@/api/newPet'

export default {
  data() {
    return {
      videoUrl: '',
      dateList: [
        {
          week: '星期五',
          date: '2024-2-14',
          times: ['10点', '14点', '16点', '18点']
        },
        {
          week: '星期六',
          date: '2024-2-15',
          times: ['10点', '14点', '16点', '18点']
        }
      ],
      activeKey: 0,
      timeCurt: null,
      loading: false,
      isShow: true,
      labelCol: {
        span: 8
      },
      content: '',
      content2: '',
      editorOption: {
        placeholder: '请输入',
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              ['blockquote', 'code-block'], // 引用  代码块
              [{ header: 1 }, { header: 2 }], // 1、2 级标题
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              [{ script: 'sub' }, { script: 'super' }], // 上标/下标
              [{ indent: '-1' }, { indent: '+1' }], // 缩进
              // [{ direction: 'rtl' }], // 文本方向
              [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
              [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
              // [{ font: ['songti'] }], // 字体种类
              [{ align: [] }], // 对齐方式
              ['clean'], // 清除文本格式
              ['image'] // 链接、图片，需要视频的可以加上video
            ]
          }
        }
      },
      data: [
        { name: '规格1', img: '', num: 1, price: 0 },
        { name: '规格1', img: '', num: 1, price: 0 }
      ],
      columns: [
        { title: '规格名称', dataIndex: 'name', align: 'center', width: 140, scopedSlots: { customRender: 'name' } },
        {
          title: '规格图片',
          dataIndex: 'img',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'img' }
        },
        { title: '规格库存', dataIndex: 'num', align: 'center', width: 70, scopedSlots: { customRender: 'num' } },
        {
          title: '规格价格（元）',
          dataIndex: 'price',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'price' }
        },
        // 查看显示
        {
          title: '已售销量',
          dataIndex: 'sales',
          align: 'center',
          width: 90,
          scopedSlots: { customRender: 'sales' }
        },
        {
          title: '操作',
          fixed: 'right',
          dataIndex: 'action',
          width: 160,
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],

      wrapperCol: {
        span: 16
      },
      details: {},
      showModal: false,
      titles: '新增',
      info: {},
      form: this.$form.createForm(this),
      token: '',
      fileList: [],
      cateList: [],
      cateList2: [],
      cate2List: [],
      storeList: []
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.token = storage.get(ACCESS_TOKEN)
    this.loadData()
  },
  components: {
    quillEditor
  },
  methods: {
    async loadData() {
      const res = await productList({ type: 1, parentId: 0 })
      this.cateList = res
      const res2 = await storelist()
      this.storeList = res2


    },
    handleChange(info) {
      console.log(info)
      let fileList = [...info.fileList]

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-1)

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.data
          this.videoUrl = file.response.data
        }
        return file
      })
      console.log(fileList)
      this.fileList = fileList
    },
    changeTime(index) {
      this.timeCurt = index
    },
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    // 内容改变事件，只需要这一个方法就够了
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.content = html
    },
    onEditorBlur2(quill) {
      console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus2(quill) {
      console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady2(quill) {
      console.log('editor ready!', quill)
    },
    // 内容改变事件，只需要这一个方法就够了
    onEditorChange2({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.content2 = html
    },
    formgetFileLength(type) {
      //获取图片
      return get(this.form.getFieldValue(type), 'length') || 0
    },
    formuploadSuccess(data, type) {
      this.form.setFieldsValue({
        picUrls: [...this.form.getFieldValue(type), data.path]
      })
    },
    formuploadSuccess2(data, type) {
      this.form.setFieldsValue({
        videoUrl: [data.path]
      })
    },
    changeSelect(e) {
      console.log(e)
    },
    async changeSelectCate(e) {
      const res = await productList({ type: 1, parentId: e })
      this.cateList2 = res
      this.form.setFieldsValue({
        firstCategoryId: e
      })
    },
    async changeSelectCate2(e) {
      this.form.setFieldsValue({
        secondCategoryId: e
      })
    },
    onChange(e) {
      this.form.setFieldsValue({
        storeId: e
      })
    },
    onChange2(e) {
      this.form.setFieldsValue({
        onsit: e
      })
    },
    cancel() {
      this.form.resetFields()
      this.showModal = false
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        console.log(err)
        if (!err) {
          // this.loading = true
          const { info } = this
          let data = {
            id: info && info.id ? info.id : undefined,

            ...this.$utils.trimValue(values),
             status: typeof values.status === 'undefined' ? 0 : values.status ? 1: 0
          }
          data.description = this.content
          data.notes = this.notes
          data.videoUrl = this.videoUrl
          const fun = info && info.id ? serviceupdate : servicecreate
          console.log(123)
          fun(data)
            .then(() => {
              this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
              this.$emit('upload')
              this.cancel()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    getData() {
      this.loading = true
      deductionDetail({ id: 1 })
        .then(data => {
          this.details = data
        })
        .finally(() => (this.loading = false))
    },
    async open(data) {
      // this.info = data
      // console.log(data, '111111')
      if (data.id) {
        this.titles = '修改'
        const res = await serviceget({ id: data.id })
        this.info = res
      } else {
        this.titles = '新增'
      }
      this.showModal = true
      this.videoUrl = this.info.videoUrl
      this.content = this.info.description
      this.content2 = this.info.notes
      // images:['https://img2.baidu.com/it/u=1906732828,3160455141&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666']
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: this.info.name,
          storeId: this.info.storeId,
          firstCategoryId: this.info.firstCategoryId,
          secondCategoryId: this.info.secondCategoryId,
          price: this.info.price,
          salesCount: this.info.salesCount,
          status: this.info.status,
          onsit: this.info.onsit,
          picUrls: this.info.picUrls ? this.info.picUrls : '',
          introduction: this.info.introduction,
          videoUrl: this.info.videoUrl,
          content: this.info.description,
          content2: this.info.notes,
        })
      })
      // this.$emit('upload')
      // this.$nextTick(() => {
      //     this.form.setFieldsValue({
      // 					...res
      // 				})

      // 			})
    }
  }
}
</script>
<style lang='less' scoped>
.time {
  display: flex;
  flex-wrap: wrap;

  div {
    width: 150px;
    height: 50px;
    border: 1px solid #efefef;
    margin-right: 10px;
    margin-bottom: 10px;
    text-align: center;
    line-height: 50px;
    color: #000;
    cursor: pointer;
  }

  .active {
    background: #1890ff;
    color: #fff;
  }
}

/deep/ .ant-form-item-label {
  // width: 100px;
}
</style>
